# This playbook is used to rebuild staging Koschei database.
# Useful to be ran after synchronization of staging Koji DB
# with production, which breaks Koschei - old builds from before sync
# have conflicting IDs with post-sync builds.
#
# In future, this playbook may be extended to sync content from
# production Koschei database dump, but this is not needed for now.

- name: stop koschei staging services
  hosts: koschei-backend-stg:koschei-web-stg
  user: root
  vars_files:
   - /srv/web/infra/ansible/vars/global.yml
   - /srv/private/ansible/vars.yml
   - /srv/web/infra/ansible/vars/{{ ansible_distribution }}.yml
  handlers:
  - import_tasks: "{{ handlers_path }}/restart_services.yml"

  tasks:
  - service: name={{ item }} state=stopped
    when: '"backend" in ansible_hostname'
    with_items: "{{ koschei_backend_services }}"
  - service: name=httpd state=stopped
    when: '"web" in ansible_hostname'

- name: drop and recreate koji-related tables
  hosts: koschei-backend-stg
  user: root
  become: yes
  become_user: koschei
  become_method: sudo
  vars_files:
   - /srv/web/infra/ansible/vars/global.yml
   - /srv/private/ansible/vars.yml
   - /srv/web/infra/ansible/vars/{{ ansible_distribution }}.yml
  handlers:
  - import_tasks: "{{ handlers_path }}/restart_services.yml"

  tasks:
  - shell: >
      koschei-admin psql <<< "
      BEGIN;
      SET LOCAL bdr.permit_ddl_locking = true;
      UPDATE base_package SET all_blocked = true;
      UPDATE collection SET latest_repo_id = null, latest_repo_resolved = null;
      DROP TABLE buildroot_problem;
      DROP TABLE package CASCADE;
      DROP TABLE build CASCADE;
      DROP TABLE applied_change CASCADE;
      DROP TABLE unapplied_change CASCADE;
      DROP TABLE dependency CASCADE;
      DROP TABLE koji_task CASCADE;
      DROP TABLE resolution_change CASCADE;
      DROP TABLE resolution_problem CASCADE;
      DROP TABLE copr_rebuild_request CASCADE;
      DROP TABLE copr_resolution_change CASCADE;
      DROP TABLE copr_rebuild CASCADE;
      DROP TABLE scalar_stats CASCADE;
      DROP TABLE resource_consumption_stats CASCADE;
      COMMIT;
      "
  - command: koschei-admin create-db

- name: bring koschei staging services up
  hosts: koschei-backend-stg:koschei-web-stg
  user: root
  vars_files:
   - /srv/web/infra/ansible/vars/global.yml
   - /srv/private/ansible/vars.yml
   - /srv/web/infra/ansible/vars/{{ ansible_distribution }}.yml
  handlers:
  - import_tasks: "{{ handlers_path }}/restart_services.yml"

  tasks:
  - service: name={{ item }} state=started
    when: '"backend" in ansible_hostname'
    with_items: "{{ koschei_backend_services }}"
  - service: name=httpd state=started
    when: '"web" in ansible_hostname'
